/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun<iot25@lingyun>
 *                  All rights reserved.
 *
 *       Filename:  pack_data.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(13/04/25)
 *         Author:  LingYun <iot25@lingyun>
 *      ChangeLog:  1, Release initial version on "13/04/25 13:39:21"
 *                 
 ********************************************************************************/
#include<stdio.h>
#include<string.h>
#include "pack_data.h"
#include "logger.h"
int pack_data(packet_t *pack, char *data, int bytes)
{
	if ( NULL == pack || NULL == data || bytes <= 0 )
	{
		log_error("Invalid arguments: pack=%p, data=%p, bytes=%d", pack, data, bytes);
		return -1;
	}
	memset(data, 0, bytes);
	int written=snprintf(data, bytes, "id:%s|time:%s|temp:%f", pack->dev_id, pack->dev_time, pack->dev_temp);
	if (written >= bytes)
       	{
    		log_error("Buffer overflow: needed=%d, available=%d", written, bytes);
    		return -1;
	}
	log_debug("pack_data successfully");
	return 0;
}


int unpack_data(char *data, packet_t *pack)
{
	if ( NULL == data || NULL == pack )
	{
		log_error("Invalid arguments: data=%p, pack=%p", data, pack);
		return -1;
	}
	 memset(pack, 0, sizeof(packet_t));  // 正确初始化结构体
	int parsed = sscanf(data, "id:%[^|]|time:%[^|]|temp:%f", pack->dev_id, pack->dev_time, &pack->dev_temp);

	 if (parsed != 3)
	 {
        	log_error("Failed to parse data: %s (parsed %d/3 fields)", data, parsed);
        	return -1;
    	 }

    	log_debug("unpack_data successful: id=%s, time=%s, temp=%.2f",pack->dev_id, pack->dev_time, pack->dev_temp);
	return 0;
}
